<?php
	//不超时
    set_time_limit(0);
	ini_set("memory_limit","356M");
    /* 检查权限 */
    
    admin_priv('goods_export');
    $charset = empty($_POST['charset']) ? 'UTF8' : trim($_POST['charset']);
    include_once(dirname(__FILE__) . '/includes/cls_phpzip.php');
    $zip = new PHPZip;

    $where = get_export_where_sql($_POST);
    $where .= ' and g.to_d=0';
   
    /**只导出可同步更新到外网的产品**/
    if($_POST['is_sync']){
    	
    	$sql_to_export = "select group_concat(distinct log_key_id) from " . $ecs->table('goods_update_log') . "  where log_export_batch=0 order by log_id desc ";
    	$list_export_ids = $db->getOne($sql_to_export);
    	$list_export_ids = $list_export_ids?$list_export_ids:'-1';
    	$where .= "and g.goods_id in($list_export_ids)";
    }   
    
   $count_sql =  "SELECT count(1) " .
           " FROM " . $ecs->table('view_goods') . " AS g     LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id = b.brand_id " .
           " LEFT JOIN " . $ecs->table('suppliers') . " AS s  ON s.suppliers_id = g.suppliers_id  " .
           " LEFT JOIN " . $ecs->table('goods_type') . " AS d  ON d.cat_id = g.goods_type  " .
           "" . $where;
   $db_stat = $db->getOne($count_sql); 
   if(empty($db_stat)) 	sys_msg('sorry,there is no data need to be export.', 1, array(array('href'=>'goods_export.php?act=goods_export','text'=>'back')));
   $perfile = 300; 
   $for_stat  = ceil($db_stat/$perfile);   
   $for_stat  = $for_stat? $for_stat:1;
   ob_end_clean();   
   print str_pad("",256);           
   echo "<p>export starting....<hr></p>";
   ob_flush();
   flush();
   //create table 
   create_table_export();
   for($i=0;$i<$for_stat;$i++):
    	echo 'creating file,from record '.($i*$perfile+1).'&nbsp;to&nbsp;'.($i+1)*$perfile.'......<br>';
	    ob_flush();
  		flush();	
	    $sql = "SELECT g.*, b.brand_name as brandname,s.suppliers_name as suppliers_name,d.cat_name as goods_type " .
	           " FROM " . $ecs->table('view_goods') . " AS g    LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id = b.brand_id " .
	           " LEFT JOIN " . $ecs->table('suppliers') . " AS s  ON s.suppliers_id = g.suppliers_id  " .
	           " LEFT JOIN " . $ecs->table('goods_type') . " AS d  ON d.cat_id = g.goods_type  " .
	          
	           "" . $where.' limit  '.$perfile.' ';
	    $res = $db->query($sql);
	    /* csv文件数组 */
	    $goods_value = array();
	   	$goods_value['goods_name'] =  '';
		$goods_value['brand_name'] =  '';
		$goods_value['product_model'] = '';
		$goods_value['standard'] = '';		
		$goods_value['technical_parameters'] = '';
		$goods_value['main_material'] = '';
		$goods_value['shop_price'] = '';		
		$goods_value['cost'] =  '';
		$goods_value['unit'] =  '';
		$goods_value['categories_of_taxes'] = '';
		$goods_value['tax'] = '"' . $row['tax'] ;
		$goods_value['min_sale_qty'] = '';
		$goods_value['state_of_origin'] = '';
		$goods_value['production_cycle'] = '';
		$goods_value['goods_weight'] = '';
		$goods_value['gross_weight'] = '';
		$goods_value['package_size'] = '';
		$goods_value['product_certification'] = '';		
			
		/**二次调整**/
		$goods_value['attribute_230'] = '';
		$goods_value['attribute_231'] = '';
		$goods_value['attribute_232'] = '';
		$goods_value['attribute_233'] = '';
		$goods_value['attribute_234'] = '';
		$goods_value['attribute_235'] = '';
		$goods_value['attribute_236'] = '';
		$goods_value['attribute_238'] = '';
		$goods_value['attribute_237'] = '';
		
		
		$goods_value['goods_desc'] ='';
		$goods_value['goods_brief'] ='';
		
		
		
		/**二次调整**/
		$goods_value['attribute_224'] = '';
		$goods_value['attribute_226'] = '';
		$goods_value['attribute_227'] = '';
		$goods_value['attribute_228'] = '';
		$goods_value['attribute_229'] = '';
	
	
	
		
		$goods_value['cat_id'] = '';
		$goods_value['goods_sn'] = '';
		$goods_value['goods_sn2'] = '';
		$goods_value['suppliers_name'] = '';
		$goods_value['hscode'] =  '';
		
		$goods_value['original_img'] = '';
		$goods_value['goods_img'] = '';
		$goods_value['goods_thumb'] = '';
		
		
	
		$goods_value['store'] = '';
		$goods_value['websites'] = '';
		$goods_value['status'] = '';
		$goods_value['tax_class_id'] = '';
		$goods_value['visibility'] = '';
		$goods_value['goods_number'] = '';
		$goods_value['is_on_sale'] =  '';
		$goods_value['type'] = '';
		$goods_value['attribute_set'] = '';
		$goods_value['simples_skus'] = '';
		$goods_value['configurable_attributes'] = '';
		$goods_value['pageurl'] = '';
		$goods_value['sort_order'] = '';
		if($charset=='UTF8'){
			array_walk($_LANG['magento'],create_function('&$n', '$n= mb_convert_encoding($n,  "CP936","UTF-8");;')); //编码转换
		}	 
		
	    $content = '"' . implode('","', $_LANG['magento']) . "\"\n";
		unset($goods_value);
		$sql_inserts = array();
		$goods_ids = array();
		$sql_inserts_prefix = '';
	    while ($row = $db->fetchRow($res))
	    {
	 
			//change      
			$goods_value['goods_name'] =  $row['goods_name'] ;
			$goods_value['brand_name'] =  $row['brandname'] ;
			$goods_value['product_model'] = $row['product_model'] ;
			$goods_value['standard'] = $row['standard'] ;
			
			$goods_value['technical_parameters'] = $row['technical_parameters'] ;
			$goods_value['main_material'] = $row['main_material'] ;
	
			
			$goods_value['shop_price'] = $row['shop_price'] ;
			
			$goods_value['cost'] =  $row['cost'] ;
			$goods_value['unit'] =  $row['unit'] ;
			$goods_value['categories_of_taxes'] = $row['categories_of_taxes'] ;
			$goods_value['tax'] = $row['tax'] ;
			$goods_value['min_sale_qty'] = $row['min_sale_qty'] ;
			$goods_value['state_of_origin'] = $row['state_of_origin'] ;
			$goods_value['production_cycle'] = $row['production_cycle'] ;
			$goods_value['goods_weight'] = $row['goods_weight'] ;
			$goods_value['gross_weight'] = $row['gross_weight'] ;
			$goods_value['package_size'] = $row['package_size'] ;
			$goods_value['product_certification'] = $row['product_certification'] ;
		 	$db_attributes = $db->getAll("select  attr_id,group_concat(attr_value) as attr_value from  " . $ecs->table('goods_attr') . " where goods_id='".$row['goods_id']."' group by goods_id,attr_id   ");
		 	foreach($db_attributes as $v){
		 		$attributes[$v['attr_id']] = $v['attr_value'] ;;
		 	}
		 	
		 	
			/**二次调整**/
			$goods_value['attribute_230'] = $attributes['230'];
			$goods_value['attribute_231'] = $attributes['231'];
			$goods_value['attribute_232'] = $attributes['232'];
			$goods_value['attribute_233'] = $attributes['233'];
			$goods_value['attribute_234'] = $attributes['234'];
			$goods_value['attribute_235'] = $attributes['235'];
			$goods_value['attribute_236'] = $attributes['236'];
			$goods_value['attribute_238'] = $attributes['238'];
			$goods_value['attribute_237'] = $attributes['237'];
			
			$goods_value['goods_desc'] = replace_special_char($row['goods_desc'], false) ;
			$goods_value['goods_brief'] = replace_special_char($row['goods_brief'], false) ;	
			
			/**二次调整**/
			$goods_value['attribute_224'] = $attributes['224'];
			$goods_value['attribute_226'] = $attributes['226'];
			$goods_value['attribute_227'] = $attributes['227'];
			$goods_value['attribute_228'] = $attributes['228'];
			$goods_value['attribute_229'] = $attributes['229'];
			
		    //get all other_parent_ids for other_cat_id 
		    $other_cat = get_other_cat($row['goods_id']);
	        $other_cat_ids = array();
	        foreach($other_cat as $var){
	        	
	          $other_cat_ids = array_merge($other_cat_ids,get_all_parent_cat_ids($var));
	          
	        }
	        $all_cat_ids = get_all_parent_cat_ids($row['cat_id']);
			$goods_value['cat_id'] = implode(',',array_merge($all_cat_ids,array_diff($other_cat_ids,$all_cat_ids))) ;

		    $goods_value['goods_sn'] = $row['goods_sn'] ;
		    $goods_value['goods_sn2'] = $row['goods_sn2'] ;
			$goods_value['suppliers_name'] = $row['suppliers_name'] ;
			$goods_value['hscode'] =  $row['hscode'] ;
			
			$goods_value['original_img'] = $row['original_img'] ;
			$goods_value['goods_img'] = $row['original_img'] ;
			$goods_value['goods_thumb'] = $row['original_img'] ;
			
			$goods_value['store'] = "admin";
			$goods_value['websites'] = $row['websites'] ;
			$goods_value['status'] =  $row['is_delete'] ? 'Dsiabled':'Enabled';
			$goods_value['tax_class_id'] = $row['tax_class_id'] ;
			$goods_value['visibility'] = $row['visibility'] ;
			$goods_value['goods_number'] = $row['goods_number'] ;
			$goods_value['is_on_sale'] =  $row['is_on_sale'] ;
			$goods_value['type'] = $row['type'] ;
			$goods_value['attribute_set'] = $row['goods_type'] ;
			$goods_value['simples_skus'] = $row['simples_skus'] ;
			$goods_value['configurable_attributes'] = $row['configurable_attributes'] ;
			$goods_value['pageurl'] = $row['pageurl'] ;
			$goods_value['sort_order'] = $row['sort_order'] ;
			
	
	        if($charset=='UTF8'){
				array_walk($goods_value,create_function('&$n', '$n= mb_convert_encoding($n,  "CP936","UTF-8");')); //编码转换
			}
			
			$goods_value = array_map("cube",$goods_value); 
            $sql_inserts[] =  "(" . implode(', ', $goods_value) . ",1)";
			unset($goods_value);
            $goods_ids[] = $row['goods_id'];
            
			//更新到数据导出表
	     
			unset($goods_value,$row,$db_attributes,$attributes);			
	    }
	    
	 	  $ids = implode(',',$goods_ids);
	 	  
	 	  //clear before 
	 	  $db->query("delete from ecs_goods_export  where sku in(select goods_sn from ecs_goods where goods_id in($ids))");
	      //to en
		  $sql_inserts_prefix = 'INSERT INTO ecs_goods_export (' . implode(', ', $_LANG['magento']) . ',is_trans) VALUES ';
    	  $db->query($sql_inserts_prefix.implode(",",$sql_inserts)) ;
    	  
    	  //update 
	      $db->query("update " . $ecs->table('goods') . " set to_d = 1 where goods_id in($ids)"); 
	      //clear memory	
	      unset($sql_inserts_prefix,$sql_inserts,$goods_ids);
	 
	    $charset = empty($_POST['charset']) ? 'UTF8' : trim($_POST['charset']);		  
		sleep(0);     
    endfor;
    	$keys = implode(',',$_LANG['magento']);
    	$keys = str_replace(',store','',$keys);
    	//add other language
    	$lang_all = get_all_lang();
    	unset($lang_all['admin']);
    	foreach($lang_all as $k=>$v){
    		$sql = "insert into ecs_goods_export(".$keys.",store,is_trans) select ".$keys.",'$k' as store,'0' as is_trans from ecs_goods_export where store='admin' ";
       		$db->query($sql);
    	}
    	echo "<hr>complate!";
		exit();
        //查询goods_export表备份为csv文件 darren add
        $export_dir=ROOT_PATH . 'export/goods_list.csv';
        $count_sql="select count(*) from ".$ecs->table('goods_export');
        $record_count=$db->getOne($count_sql);
      
        if($record_count<=1000){
       	    
       	    if(file_exists($export_dir)){
       	    	unlink($export_dir);
       	    }
	        $sql="select * from ".$ecs->table('goods_export');
	        
	        //打开csv表写入所有字段在第一行
	        $goods_field=$db->getCol('DESC'.$ecs->table('goods_export'));
	        $fp = fopen($export_dir,"w");
			$fput = null;
			foreach($goods_field as $v) $fput[] = $v;
			fputcsv($fp,$fput);
			unset($fput); 
			
			//从下一行开始，写入所有记录
			$row=$db->getAll($sql); 
			$fput = null;
			foreach($row as $v)
			fputcsv($fp,$v);	
			unset($fput,$row);
			fclose($fp);
	       	//压缩csv为zip包
	       	$goodszip=ROOT_PATH . "export/goods_list.zip";	
	        //判断zip是否存在，存在则删除
	       	if(file_exists($goodszip)){
	       		unlink($goodszip);
	       	}	
		    $zip->zip("../export",$goodszip); 	   
	     	echo 'product export complete!';
	     	echo "<hr><p>zip file created successfully!</p>";
		    echo "<p>Memory,used&nbsp",convert_memory(memory_get_usage(true)),"</p>";
	        echo "<span><a href=\"".$goodszip."\">click here to download</a></span>";	
	
       }else{
       		echo "对不起，你导出的产品数据量超过5000，不允许下载，请重新查询导出!";
       		echo "<a href='javascript:window.history.go(-1);return false'>返回上一页</a>";
       }
       
       
//得到所有父类ID及类名称     
  function get_parent_cats($cat)
{
    if ($cat == 0)
    {
        return array();
    }

    $arr = $GLOBALS['db']->GetAll('SELECT cat_id, cat_name, parent_id FROM ' . $GLOBALS['ecs']->table('category'));

    if (empty($arr))
    {
        return array();
    }

    $index = 0;
    $cats  = array();

    while (1)
    {
        foreach ($arr AS $row)
        {
            if ($cat == $row['cat_id'])
            {
                $cat = $row['parent_id'];

                $cats[$index]['cat_id']   = $row['cat_id'];
                $cats[$index]['cat_name'] = $row['cat_name'];

                $index++;
                break;
            }
        }

        if ($index == 0 || $cat == 0)
        {
            break;
        }
    }

    return $cats;
}  
//得到所有父类ID
 function get_all_parent_cat_ids($cat_id)
 {
    $all_cat_ids=get_parent_cats($cat_id);

    foreach($all_cat_ids as $key => $v)
    {
	   $all_cat_ids[$key] = $v['cat_id'];
    }
    return $all_cat_ids;
}  
       
 ?>      
     
